package com.qf.ticketredis.controller;

import com.qf.ticketredis.pojo.Ticket;
import com.qf.ticketredis.service.TicketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

//@RestController
//@RequestMapping("/ticket")
public class TicketController {

    @Autowired
    private TicketService ticketService;

    @GetMapping("/sell/{id}")
    public void sell(@PathVariable("id") Integer id) throws InterruptedException {

        /*
            synchronized只能解决当个进程中的多个线程的并发安全问题
            对于多个进程的并发安全问题，需要使用分布式锁解决
         */
        while (true){
            synchronized (this) {
                //查询id对应的票务信息，是否有剩余票
                Ticket ticket = ticketService.getById(id);
                Integer count = ticket.getCount();
                if (count > 0) {
                    System.out.println("正在卖出第" + count + "张票");
                    //模拟卖票时间
                    Thread.sleep(1000);

                    count = count - 1;

                    //重新更新数据库的票务信息
                    ticket.setCount(count);
                    ticketService.updateById(ticket);
                    System.out.println("剩余票数为：" + count);
                } else {
                    break;
                }
            }
        }
    }
}
